﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;

namespace SPQueryToSql.ApplicationObjects.CAML
{
    internal class OrderBy
    {
        public List<FieldRef> FieldRefs;

        public OrderBy(XContainer element)
        {
            FieldRefs = new List<FieldRef>();
            foreach (var child in element.Elements())
            {
                FieldRefs.Add(new FieldRef(child));
            }
        }

        public string ToRowNumberSql(List<FieldInfo> fields)
        {
            if (FieldRefs.Count == 0)
                return @"tp_Ordering";
            return string.Join(", ", (FieldRefs.Where(x => x != null).Select(
                fr => new {fr, lf = fields.FirstOrDefault(f => f.InternalName == fr.Name)}).Select(
                    @t => string.Format("{0} {1}", @t.lf.ColumnName, (@t.fr.Ascending == true ? "ASC" : "DESC")))).ToArray());
        }

        public override string ToString()
        {
            var sb = new StringBuilder();
            sb.Append("<OrderBy>");
            sb.Append(Environment.NewLine);
            foreach (var fr in FieldRefs)
            {
                sb.Append(fr.ToString(1));
            }
            sb.Append("</OrderBy>");
            return sb.ToString();
        }
    }
}
